package label

import (
	"context"
	"gitee.com/bobo-rs/idea-space-framework/framework/dao"
	"gitee.com/bobo-rs/idea-space-framework/framework/model"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
)

// ProcessGetLabelValueList 处理并获取标签值列表
func (l *sLabel) ProcessGetLabelValueList(ctx context.Context, where interface{}, rows interface{}) error {
	err := dao.LabelValues.Ctx(ctx).
		Where(where).
		Scan(rows)
	if err != nil {
		return err
	}
	return nil
}

// CheckLabelValueExists 检测标签值是否存在
func (l *sLabel) CheckLabelValueExists(ctx context.Context, where interface{}) (bool, error) {
	total, err := dao.LabelValues.Ctx(ctx).
		Where(where).
		Count()
	if err != nil {
		return false, err
	}
	return total > 0, nil
}

// ProcessLabelValueCount 获取标签数量
func (l *sLabel) ProcessLabelValueCount(ctx context.Context, where interface{}) int {
	if where == nil || g.IsNil(where) {
		return 0
	}
	total, _ := dao.LabelValues.Ctx(ctx).Where(where).Count()
	return total
}

// ProcessLabelValueDetailByHash 以hash值获取标签值详情
func (l *sLabel) ProcessLabelValueDetailByHash(ctx context.Context, hash string, detail interface{}) error {
	if len(hash) != 32 {
		return gerror.New(`标签值hash类型错误`)
	}
	return l.ProcessLabelValueDetail(ctx, g.Map{`hash`: hash}, detail)
}

// ProcessLabelValueDetailByValueAndLabelId 通过标签ID和标签值获取标签值详情
func (l *sLabel) ProcessLabelValueDetailByValueAndLabelId(ctx context.Context, where model.LabelValueItem, detail interface{}) error {
	if len(where.Value) == 0 || where.LabelId == 0 {
		return gerror.New(`标签ID和标签值不能为空`)
	}
	return l.ProcessLabelValueDetail(ctx, where, detail)
}

// ProcessLabelValueDetail 处理并获取标签值详情
func (l *sLabel) ProcessLabelValueDetail(ctx context.Context, where interface{}, detail interface{}) error {
	err := dao.LabelValues.Ctx(ctx).
		Where(where).
		Scan(detail)
	if err != nil {
		return err
	}
	return nil
}

// ProcessLabelValueMapByLabelId 根据标签ID获取并处理标签值MAP
func (l *sLabel) ProcessLabelValueMapByLabelId(ctx context.Context, labelId ...uint) (map[uint]string, error) {
	if len(labelId) == 0 || (len(labelId) > 0 && labelId[0] == 0) {
		return nil, gerror.New(`缺少标签ID`)
	}
	// 获取数据列表
	list := []model.LabelValueItem{}
	err := l.ProcessGetLabelValueList(
		ctx,
		g.Map{dao.LabelValues.Columns().LabelId: labelId},
		&list,
	)
	if err != nil {
		return nil, err
	}
	// 初始化
	valuesMap := make(map[uint]string)
	for _, item := range list {
		// 拼接标签值
		if _, ok := valuesMap[item.LabelId]; ok {
			valuesMap[item.LabelId] += "," + item.Value
			continue
		}
		valuesMap[item.LabelId] = item.Value
	}
	return valuesMap, nil
}
